<!-- 质量日报-质量问题情况 -->
<template>
  <div class="std-operation-rate-management">
    <el-container>
      <el-header>
        <div class="common-div-card management-header">
          <el-form :inline="true" :model="searchForm" class="management-header-form">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="searchForm.startTime"
                type="datetime"
                placeholder="开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :size="headerSize"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="searchForm.endTime"
                type="datetime"
                placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :size="headerSize"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item label="区域">
              <el-select v-model="searchForm.area" clearable style="width: 120px" :size="headerSize">
                <el-option label="一冷" value="一冷" />
                <el-option label="三冷" value="三冷" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleInsert" :size="headerSize">新增</el-button>
              <el-button type="primary" @click="handleSearch" :size="headerSize">查询</el-button>
              <el-button @click="handleReset" :size="headerSize">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>

      <el-main>
        <el-col>
          <el-row>
            <div style="width: 100%" class="common-div-card management-table">
              <el-table
                :data="tableData"
                border
                :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :stripe="true"
                v-loading="tableLoading"
                :show-overflow-tooltip="true"
                ref="tableRef"
              >
                <el-table-column type="index" :index="indexMethod" label="序号" width="80" />
                <el-table-column prop="yearMonthDay" label="年月日" />
                <el-table-column prop="area" label="区域" />
                <el-table-column prop="createTime" label="创建时间" :formatter="formatDate" />

                <el-table-column label="操作" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-row>
          <el-row>
            <!-- 分页区域 -->
            <div class="common-div-card management-pagination">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </div>
          </el-row>
        </el-col>
      </el-main>
    </el-container>
  </div>

  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :before-close="handleClose"
    :close-on-click-modal="false"
    ref="detailDialogRef"
    @closed="cancel"
    class="detailDialog"
  >
    <div>
      <el-form :model="dialogForm" label-width="120px" :rules="rules" ref="dialogFormRef">
        <!-- ref="form"  -->
        <el-table :data="dialogFormtableData" style="width: 100%">
          <el-table-column prop="area" label="区域" width="100">
            <template #default="scope">
              <el-input type="string" v-model="area" />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单元" width="70"> </el-table-column>
          <el-table-column prop="belong" label="归属" width="60"> </el-table-column>
          <el-table-column prop="yearMonthDay" label="年月日" width="160">
            <template #default="scope">
              <el-date-picker v-model="dialogForm.yearMonthDay" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </template>
          </el-table-column>

          <el-table-column prop="one" label="原品种一次合格率(%)">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.one" />
            </template>
          </el-table-column>
          <el-table-column prop="two" label="废次降率(%)">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.two" />
            </template>
          </el-table-column>
          <el-table-column prop="three" label="封闭返工(吨)">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.three" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="dialogFormSubmit"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessageBox } from 'element-plus';
  import { listApiMainCompletion } from '/@/api/report/quality/index';
  import dayjs from 'dayjs';

  const dialogFormtableData = ref([
    {
      area: '三冷',
      unit: '酸轧',
      belong: '生产',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '酸轧',
      belong: '设备',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '连退',
      belong: '生产',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '连退',
      belong: '设备',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '5#镀锌',
      belong: '生产',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '5#镀锌',
      belong: '设备',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '保障',
      belong: '磨辊',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '保障',
      belong: '公辅',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '保障',
      belong: '运转',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
    {
      area: '三冷',
      unit: '其它',
      belong: '其它',
      yearMonthDay: '',
      one: 0,
      two: 0,
      three: 0,
    },
  ]);
  const area = ref();

  interface SearchForm {
    startTime: string;
    endTime: string;
    area: '';
    unit: '';
    belong: '';
  }

  interface tableRow {
    id: number;
    area: string; // 区域
    unit: string; // 单元
    belong: string; // 归属-归户（生产、设备、磨辊、公辅、运转）
    yearMonthDay: string; // 年月日
    mainTable: mainTable[];
  }

  interface mainTable {
    one: number;
    two: number;
    three: number;
  }

  const searchForm = reactive<SearchForm>({
    startTime: '',
    endTime: '',
    area: '',
    unit: '',
    belong: '',
  });

  const tableLoading = ref(false);
  const tableRef = ref<any>();
  const dialogVisible = ref(false);
  const dialogTitle = ref('新增');
  const dialogFormRef = ref();
  const headerSize = ref('small');
  const viewportWidth = ref();
  function formatDate(_row: any, _column: any, cellValue: any) {
    if (!cellValue) return '';
    return dayjs(cellValue).format('YYYY-MM-DD HH:MM:ss');
  }

  const indexMethod = (index: number) => {
    return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
  };

  const rules = {
    area: [{ required: true, type: 'string', message: '请选择区域' }],
    unit: [{ required: true, type: 'string', message: '请选择单元' }],
    belong: [{ required: true, type: 'string', message: '请选择归属' }],
    yearMonthDay: [{ required: true, type: 'string', message: '请选择年月日' }],
  };

  const tableData = ref<tableRow[]>([]);

  // 弹窗表单
  const dialogForm = reactive<tableRow>({
    id: 0,
    area: '一冷', // 区域
    unit: '三冷', // 单元
    belong: '生产', // 归属-归户（生产、设备、磨辊、公辅、运转）
    yearMonthDay: '', // 年月日
    mainTable: [],
  });

  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 重置方法
  const handleReset = () => {
    (Object.keys(searchForm) as Array<keyof SearchForm>).forEach((key) => {
      searchForm[key] = '';
    });
    pagination.currentPage = 1;
    handleSearch();
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 添加方法
  const handleInsert = () => {
    dialogTitle.value = '新增';
    dialogVisible.value = true;
    // 初始化表单
    area.value = '三冷';
    dialogForm.area = '三冷';
    dialogForm.unit = '酸轧';
    dialogForm.belong = '生产';
    dialogForm.yearMonthDay = dayjs().format('YYYY-MM-DD');
    // 将明细表置零
    dialogFormtableData.value = (dialogFormtableData.value || []).map((item: any) => ({
      ...item,
      one: 0,
      two: 0,
      three: 0,
    }));
  };

  // 编辑方法
  const handleEdit = async (row: any) => {
    dialogTitle.value = '编辑';
    dialogVisible.value = true;

    dialogFormtableData.value = row.mainTable;
    area.value = row.area;
    dialogForm.yearMonthDay = row.yearMonthDay;
    dialogForm.area = row.area;
    dialogForm.id = row.id;
    //Object.assign(dialogFormtableData, { ...row });
  };

  // 删除方法
  const handleDelete = async (row: any) => {
    ElMessageBox.confirm('确认删除该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const param = {
            id: row.id,
            yearMonthDay: row.yearMonthDay,
            area: row.area,
          };
          await listApiMainCompletion.delete(param).then((res) => {
            if (res.data.status != 2000) {
              throw new Error('数据删除失败：' + res.data.message);
            }
            ElNotification({
              title: '数据删除成功',
              message: res.data.msg ?? '',
              type: 'success',
              duration: 2000,
            });
          });
        } catch (error) {
          console.log('删除失败：' + error);
          ElMessage.error('删除失败');
        } finally {
          fetchTableData();
        }
      })
      .catch(() => {
        // 用户取消，无需处理
      });
  };

  // 详情弹窗关闭事件
  const handleClose = () => {
    ElMessageBox.confirm('确定要放弃当前更改吗?')
      .then(() => {
        cancel();
      })
      .catch(() => {
        // catch error
      });
  };

  // 详情弹窗取消事件
  const cancel = () => {
    dialogForm.area = '';
    dialogForm.unit = '';
    dialogForm.belong = '';
    dialogForm.yearMonthDay = '';
    dialogForm.mainTable = [];
    dialogVisible.value = false;
    dialogFormRef.value && dialogFormRef.value.resetFields && dialogFormRef.value.resetFields();
  };

  // 编辑提交
  const dialogFormSubmit = async () => {
    console.log('dialogForm' + area.value);
    dialogFormRef.value
      .validate()
      .then(async () => {
        const payload = {
          id: dialogForm.id,
          yearMonthDay: dialogForm.yearMonthDay,
          area: area.value,
          mainTable: (dialogFormtableData.value || []).map((item: any) => ({
            one: Number(item.one) || 0,
            two: Number(item.two) || 0,
            three: Number(item.three) || 0,
          })),
        };

        let res;
        if (dialogTitle.value === '编辑') {
          res = await listApiMainCompletion.edit(payload);
        } else {
          res = await listApiMainCompletion.insert(payload);
        }
        if (res.data.status != 2000) {
          throw new Error('数据录入失败：' + (res.data.message ?? ''));
        }
        ElNotification({
          title: '数据录入成功',
          message: '',
          type: 'success',
          duration: 2000,
        });
        dialogVisible.value = false;
        fetchTableData();
      })
      .catch((error: any) => {
        dialogVisible.value = false;
        fetchTableData();
        ElNotification({
          title: '数据获取失败',
          message: error.message ?? '',
          type: 'error',
          duration: 2000,
        });
        console.error('数据登录失败:', error);
      });
  };

  const fetchTableData = async () => {
    try {
      tableLoading.value = true;
      const param = {
        dbegin: searchForm.startTime,
        dend: searchForm.endTime,
        area: searchForm.area,
        belong: searchForm.belong,
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
      };
      await listApiMainCompletion.page(param).then((res) => {
        if (res.data.status != 2000) {
          throw new Error('数据获取失败：' + res.data.message);
        }
        tableData.value = res.data.data;
        pagination.total = res.data.count;
      });
      tableLoading.value = false;
    } catch (error: any) {
      ElNotification({
        title: '数据获取失败',
        message: error.message ?? '',
        type: 'error',
        duration: 2000,
      });
    } finally {
      tableLoading.value = false;
    }
  };

  onMounted(() => {
    viewportWidth.value = window.innerWidth;
    headerSize.value = viewportWidth.value == 1920 ? '' : 'small';
    fetchTableData();
  });
</script>

<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border:1px solid #dcdfe6;

  .std-operation-rate-management {
    background-color: #fff;
  }

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .management-header {
    display: flex;
    flex: 1;
    justify-content: flex-start;
    align-items: center;
    padding: 20px;
    height: 10vh;
  }

  .management-header-form {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .management-table {
    width: 100%;
    height: 70vh;
    padding: 20px;
    margin-top: 2vh;

    .el-table {
      height: calc(70vh - 40px);
    }
  }

  .management-pagination {
    width: 100%;
    height: 6vh;
    margin-top: 1vh;
    display: flex;
    justify-content: flex-end;
    padding: 20px;
  }

  .form-inline {
    display: flex;
    flex-wrap: nowrap;
    flex-direction: row;
  }

  .detailDialog {
    width: 1300px; //auto
    overflow: auto;
  }

  .grid-form {
    display: grid;
    grid-template-columns: repeat(10, 1fr); /* 10列 */
    gap: 10px; /* 间距 */
  }
</style>
